package cassandrawindow;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;

/**
 *
 * @author quyennb
 */
public class HandleCoverPageV2 {

    public static final int NUMBER_NEWS_COVER_PAGE           = 40;

    //sort value of result
        static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
            SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
                new Comparator<Map.Entry<K,V>>() {
                    @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
                        int res = e1.getValue().compareTo(e2.getValue());
                        return res != 0 ? res : 1; // Special fix to preserve items with equal values
                    }
                }
            );
            sortedEntries.addAll(map.entrySet());
            return sortedEntries;
        }

        public void handleData(){
            MysqlDataManager mysql = new MysqlDataManager();            
            /*lay nhung tin xuat hien tren nhieu bao nhat
             * sau Ä‘Ã³ nhá»¯ng tin cÃ²n láº¡i thÃ¬ láº¥y hÃªt á»Ÿ bÃ¡o dan tri,nhÆ°ng khong duoc trung nhau
             * nhung tin nÃ o trÃ¹ng nhau nháº¥t cho rank = 1
             * náº¿u trung nhau Ã­t hÆ¡n thi cho rank random
             */
            //1.láº¥y nhÆ°ng tin trung nhau nháº¥t (la tin hot nhÃ¢t)                               
            //get currentDate
            String currentDate = TimeUtil.getCurrentTimeInString();//2012-07-24
            
            Map<Long, Long> hotNews = new HashMap<>();
            mysql.getDuplicateHotNews(currentDate,hotNews);
            System.out.println("hot new:"+hotNews);
            
            //2.lay nhung tin con lai tren bao dan tri ,id =1
            Map<Long, Long> allHotNewBySourceId = new HashMap<>();
            //
            for(int i = 1 ; i <= 7; i++)
            {
                Map<Long, Long> map1 = new HashMap<>();
                map1 = mysql.getAllHotNewBySourceId(i,currentDate);
                allHotNewBySourceId.putAll(map1);
                //neu lay tong so tin hot va tin hot tren 1 bao khong bang 10 thi phai tim bao khac
                if(allHotNewBySourceId.size() + hotNews.size() >= NUMBER_NEWS_COVER_PAGE)
                {                    
                    break;
                } 
            }
            //3.lay nhung hot_id cua nhung tin trung nhau 
            List infor = new ArrayList();   
            Set s = hotNews.entrySet();
            Iterator it=s.iterator();
            while(it.hasNext())
            {
                Map.Entry m =(Map.Entry)it.next();
                //key la userid
                long key=(Long)m.getKey();
                mysql.getHotNewByCrawlerId(infor,key);
            }
            //4. check voi nhung id tren bao dan tri va danh lai rank
            //Map<Integer, Integer> valRets = new HashMap<>();
            Set s1 = allHotNewBySourceId.entrySet();
            Iterator it1=s1.iterator();
            int countHotNewCoverPage = hotNews.size();
            SqlServerDataManager sqlserver = new SqlServerDataManager();
            StringBuilder sb = new StringBuilder();
            sqlserver.deltHotNewsCoverPage();
            //neu so tin trung nhau < 10
            if(countHotNewCoverPage < NUMBER_NEWS_COVER_PAGE)
            {
                    while(it1.hasNext())
                    {
                        Map.Entry m =(Map.Entry)it1.next();
                        //key la userid
                        long key=(Long)m.getKey();
                        //neu khong trung voi nhung id da lay thi add vao map moi
                        if(!infor.contains(key))
                        {
                            countHotNewCoverPage ++;
                            hotNews.put((Long) m.getValue(), 1L);
                            if(countHotNewCoverPage == NUMBER_NEWS_COVER_PAGE) break;
                        }
                    }

                    //5.gan 2 map vao : valRets & hotNews va lay gia tri
                    //map moi nay se co key la id va value tu 1-> n,n la so lan lap nhieu nhat
                    //del hot new cu va insert hot new moi                    
                    Debug.println("sucess");
                    //StringBuilder sb = new StringBuilder();
                    int rank = NUMBER_NEWS_COVER_PAGE;
                    for (Entry<Long, Long> entry  : entriesSortedByValues(hotNews)) {
                        System.out.println(entry.getKey()+":"+entry.getValue());
                        long NewsID = entry.getKey();
                        //if exist
                        String strSQL = mysql.getAllValueHotNewCoverPageByNewsId(NewsID, rank,currentDate);
                        Debug.println(strSQL);
                        //insert in db
                        sqlserver.insertHotNewCoverPage(strSQL);
                        rank --;                                             
                    }                    
            }
            //neu so tin trung nhau > 10
            else {                    
                    int rank = NUMBER_NEWS_COVER_PAGE;
                    int inteval = countHotNewCoverPage - NUMBER_NEWS_COVER_PAGE;
                    int checkBreak = 0 ;
                    
                    for (Entry<Long, Long> entry  : entriesSortedByValues(hotNews)) {
                        checkBreak ++;
                        if(checkBreak <= inteval) continue;
                        System.out.println(entry.getKey()+":"+entry.getValue());
                        long NewsID = entry.getKey();
                        //if exist
                        if(sqlserver.checkExistByNewsId(NewsID))
                        {
                            //if not is selected
                            if(!sqlserver.checkIsSelectedByNewsId(NewsID))
                            {
                                //update in db
                                sqlserver.updateRankByNewsId(NewsID, rank);
                                Debug.println("update successfully");
                            }
                            //if is selected -> nothing
                        } else {
                                String strSQL = mysql.getAllValueHotNewCoverPageByNewsId(NewsID, rank,currentDate);
                                Debug.println(strSQL);
                                //insert in db
                                sqlserver.insertHotNewCoverPage(strSQL);
                        }
                        rank --; 
                    }                    
            }           
    }

}
